package me.militch.quickcore.execute;

import io.reactivex.Flowable;
import me.militch.quickcore.util.ApiException;
import me.militch.quickcore.util.EventCall;
import me.militch.quickcore.mvp.model.ModelHelper;
import me.militch.quickcore.util.RespBase;
import me.militch.quickcore.event.ViewEvent;

public class ViewExecute<V> {
    private V view;
    private ModelHelper modelHelper;
    protected ViewExecute(V view){
        this.view = view;
    }
    protected V getView() {
        return view;
    }
    public static <V> ViewExecute<V> bind(V view){
        return new ViewExecute<V>(view);
    }
    public ViewExecute<V> setModelHelper(ModelHelper modelHelper){
        this.modelHelper = modelHelper;
        return this;
    }
    public <D> ViewExecute<V> toDo(Flowable<RespBase<D>> respResult, final ViewEvent<V,D> okVt, final ViewEvent<V,ApiException> eVt){
        if(modelHelper == null||view == null){
            return null;
        }
        modelHelper.request(respResult, new EventCall<D>() {
            @Override
            public void call(D t) {
                if(okVt != null)
                    okVt.call(view, t);
            }
        }, new EventCall<ApiException>() {
            @Override
            public void call(ApiException e) {
                if(eVt != null)
                    eVt.call(view,e);
            }
        });
        return this;
    }
    public <D> ViewExecute<V> toDo(Flowable<RespBase<D>> respResult, final ViewEvent<V,D> okVt){
        return toDo(respResult,okVt,null);
    }
}
